<!-- 聊天界面 -->
<template>
  <div>
    <navigationBar></navigationBar>
    <div class="home">
      <el-container height="100%">
        <el-main>
          <chatHome @send="send" ref="chatHome"></chatHome>
        </el-main>
      </el-container>
    </div>
  </div>
</template>

<script>
import navigationBar from "@/components/navigationBar.vue";
import chatHome from "./chatHome";
import io from "socket.io-client";
import { getToken } from "@/utils/auth";
export default {
  name: "chat",
  components: {
    navigationBar,
    chatHome,
    io,
  },
  data() {
    return {
      path: "ws://127.0.0.1:8888/ws",
      socket: "",
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      if (typeof WebSocket === "undefined") {
        alert("您的浏览器不支持socket");
      } else {
        //实例化wocket
        let token;
        if (getToken()) {
          this.socket = new WebSocket(this.path);

          //监听socket连接
          this.socket.onopen = this.open;
          //监听socket错误信息
          this.socket.onerror = this.error;
          //监听socket消息
          this.socket.onmessage = this.getMessage;
        } else {
          console.log("登录信息过期");
          // this.$msgbox
          //   .confirm(
          //     "登录状态已过期，您可以继续留在该页面，或者重新登录",
          //     "系统提示",
          //     {
          //       confirmButtonText: "重新登录",
          //       cancelButtonText: "取消",
          //       type: "warning",
          //     }
          //   )
          //   .then(() => {
          //     //记录跳转登录界面前的页面路由地址
          //     localStorage.setItem("logUrl", router.currentRoute.fullPath);
          //     router.push({
          //       path: "/login",
          //     });
          //   })
          //   .catch(() => {});
        }
      }
    },
    open() {
      console.log("连接成功");
      let authMsg = JSON.stringify({
        type: "0",
        data: getToken(),
      });
      this.socket.send(authMsg);
    },
    error() {
      console.log("连接失败");
    },
    getMessage(res) {
      let user = JSON.parse(localStorage.getItem('userInfo'))
      // console.log(user)
      let result = JSON.parse(res.data);
      console.log("accpet-1：", result);
      console.log(result.data.createBy,user)
      if(result.data.createBy != user.id){
        this.$bus.$emit("onMessage", result.data);
      }
      
    },
    close() {
      // console.log("socket已经关闭");
    },
    send(msg) {
      let msgJson = JSON.stringify(msg);
      this.socket.send(msgJson);
    },
  },
  destroyed() {
    if (this.socket) {
      this.socket.close();
      this.socket.onclose = function (evt) {
        console.log("websocket已关闭");
      };
    }
  },
};
</script>


<style scoped>
.home {
  width: 90vw;
  height: 90vh;
  background-color: rgb(39, 42, 55);
  border-radius: 15px;
  position: absolute;
  left: 50%;
  top: 55%;
  transform: translate(-50%, -53%);
}
</style>